from datetime import datetime
from typing import Optional, Dict, Any
from apps.models.models import User, User_Profiles, Student, Coach
from apps.schemas.schemas import ProfileUpdateRequest
from tortoise.exceptions import DoesNotExist


async def get_user_profile(user_id: int) -> Dict[str, Any]:
    """
    根据user_id获取用户的详细信息
    :param user_id: 用户ID
    :return: 用户详细信息
    """
    try:
        # 获取用户详细信息
        user_profile = await User_Profiles.get(user_id=user_id)

        # 返回用户详细信息
        result = {
            "profile_id": user_profile.profile_id,
            "user_id": user_profile.user_id_id,  # 数据库中的实际外键值
            "fullname": user_profile.fullname,
            "gender": user_profile.gender,
            "birthday": user_profile.birthday,
            "id_number": user_profile.id_number,
            "address": user_profile.address
        }

        return result
    except DoesNotExist:
        raise ValueError("用户详细信息不存在")
    except Exception as e:
        raise Exception(f"Error retrieving user profile: {str(e)}")


async def update_profile(user_id: int, data: ProfileUpdateRequest) -> bool:
    """
    根据user_id更新用户信息（不区分学生还是教练）
    :param user_id: 用户ID
    :param data: 用户信息更新请求数据
    :return: 更新是否成功
    """
    try:
        # 查询用户是否存在
        user = await User.get_or_none(user_id=user_id)
        if not user:
            raise ValueError("User not found")

        # 查询用户详细信息
        profile = await User_Profiles.get_or_none(user_id=user_id)
        if not profile:
            raise ValueError("User profile not found")

        update_data = data.dict(exclude_unset=True)  # 只获取提供的字段

        # 只更新 User_Profiles 表中的字段（姓名、性别、出生日期、身份证号和地址）
        profile_fields = ['fullname', 'gender', 'birthday', 'id_number', 'address']
        if any(k in update_data for k in profile_fields):
            # 检查身份证号是否已被其他用户使用
            if 'id_number' in update_data:
                existing_profile = await User_Profiles.get_or_none(id_number=update_data['id_number'])
                if existing_profile and existing_profile.user_id_id != user_id:
                    raise ValueError("ID number already exists")

            await profile.update_from_dict({
                k: v for k, v in update_data.items()
                if k in profile_fields
            }).save()

        return True
    except DoesNotExist:
        raise ValueError("User or profile not found")
    except Exception as e:
        raise Exception(f"Error updating profile: {str(e)}")
